<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 船期码管理
 *
 */
class Vesselvoy extends Backend
{
    /**
     * Vesselvoy模型对象
     * @var \app\admin\model\Vesselvoy
     */
    protected $model = null;
    
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Vesselvoy;
    }

    /**
     * 编辑
     */
    public function edit()
    {

        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $row = $this->model->find(['VESSEL',$data['ids']]);
        }
        if (!$row) {
            $this->error(__('Record not found'));
        }
        $dataLimitAdminIds = $this->getDataLimitAdminIds();

        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }

                $result = $row->strict(false)->where(['VESSEL'=>$data['ids'],'DIRECTION'=>$data['DIRECTION_s'],'VOY'=>$data['VOY_s']])->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }
        $row['DIRECTION_s']=$row['DIRECTION'];
        $row['VOY_s']=$row['VOY'];
        $row['ids']=$row['VESSEL'];
        $this->success('', [
            'row' => $row
        ]);
    }

}